package com.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.pojo.Video;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.enums.PublishAuditStateEnum;
import com.tanhua.mapper.PublishInfoMapper;
import com.tanhua.pojo.PublishInfo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zmy12345
 */
@Service
public class PublishInfoService extends ServiceImpl<PublishInfoMapper, PublishInfo> {

    @DubboReference(version = "1.0.0")
    private VideoApi videoApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;


    /**
     * 根据发布id查询信息
     *
     * @param publishId
     * @return
     */
    public PublishInfo findInfoByPublishId(String publishId) {
        return super.getOne(Wrappers.<PublishInfo>lambdaQuery()
                .eq(PublishInfo::getPublishId, publishId)
        );
    }

    /**
     * 获取发布内容分页数据
     *
     * @param page      当前页码
     * @param pageSize  页尺寸
     * @param sortProp  排序字段
     * @param sortOrder ascending 升序 descending 降序
     * @param id        消息id
     * @param sd        开始时间
     * @param ed        结束时间
     * @param uid       用户ID
     * @return 发布内容分页数据
     */
    public IPage<PublishInfo> findInfoByPage(Integer page, Integer pageSize, String sortProp, String sortOrder, String id, Long sd, Long ed, Long uid, String state) {
        Page<PublishInfo> infoPage = new Page<>(page, pageSize);
        if (StrUtil.isNotEmpty(sortProp) && StrUtil.isNotEmpty(sortOrder)) {
            //设置排序
            sortProp = StrUtil.toUnderlineCase(sortProp);
            if ("ascending".equals(sortOrder)) {
                infoPage.setAsc(sortProp);
            } else {
                infoPage.setDesc(sortProp);
            }
        }
        LambdaQueryWrapper<PublishInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(id)) {
            lambdaQueryWrapper.like(PublishInfo::getUserId, id);
        }
        if (sd != null && ed != null && sd != -1 && sd.equals(ed)) {
            // 当 开始时间 和 结束时间 为相同时，即同一天。结束时间+1天毫秒数
            ed = ed + 86400000;
        }
        if (sd != null && sd > 0) {
            lambdaQueryWrapper.ge(PublishInfo::getCreateDate, sd);
        }
        if (ed != null && ed > 0) {
            lambdaQueryWrapper.le(PublishInfo::getCreateDate, ed);
        }
        if (uid != null) {
            lambdaQueryWrapper.eq(PublishInfo::getUserId, uid);
        } else {
            lambdaQueryWrapper.notIn(PublishInfo::getState, PublishAuditStateEnum.AUTO_BLOCK.getValue(), PublishAuditStateEnum.AUTO_PASS.getValue(), PublishAuditStateEnum.WAIT.getValue());
        }
        if (StrUtil.isNotEmpty(state) && !StrUtil.equals("all", state)) {
            lambdaQueryWrapper.eq(PublishInfo::getState, state);
        }
        return super.getBaseMapper().selectPage(infoPage, lambdaQueryWrapper);
    }

    /**
     * 统计发布内容
     *
     * @param id    消息id
     * @param sd    开始时间
     * @param ed    结束时间
     * @param uid   用户ID
     * @param state 审核类型
     * @return 统计数
     */
    public Long countInfo(String id, Long sd, Long ed, Long uid, String state) {
        LambdaQueryWrapper<PublishInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(id)) {
            lambdaQueryWrapper.like(PublishInfo::getUserId, id);
        }
        if (sd != null && ed != null && sd != -1 && sd.equals(ed)) {
            // 当 开始时间 和 结束时间 为相同时，即同一天。结束时间+1天毫秒数
            ed = ed + 86400000;
        }
        if (sd != null && sd > 0) {
            lambdaQueryWrapper.ge(PublishInfo::getCreateDate, sd);
        }
        if (ed != null && ed > 0) {
            lambdaQueryWrapper.le(PublishInfo::getCreateDate, ed);
        }
        if (uid != null) {
            lambdaQueryWrapper.eq(PublishInfo::getUserId, uid);
        }
        if (StrUtil.isNotEmpty(state)) {
            lambdaQueryWrapper.eq(PublishInfo::getState, state);
        }
        return super.getBaseMapper().selectCount(lambdaQueryWrapper).longValue();
    }

    /**
     * 视频上传记录
     *
     * @param page
     * @param pageSize
     * @param sortProp
     * @param sortOrder
     * @param uid
     * @return
     */
    public Object queryVideosPage(Integer page, Integer pageSize, String sortProp, String sortOrder, Long uid) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(0);
        PageInfo<Video> videoPageInfo = this.videoApi.queryVideoList(uid, page, pageSize);
        List<Video> videoList = videoPageInfo.getRecords();

        if (CollUtil.isEmpty(videoList)) {

            pageResult.setItems(Collections.emptyList());
            return pageResult;
        }

        Map<Long, UserInfo> userInfoMap =
                this.userInfoApi.queryMapByUserIdList(CollUtil.getFieldValues(videoList, "userId"));



        Map<ObjectId,Integer> commentCountMap = new HashMap<>();
        Map<ObjectId,Long> likeCountMap = new HashMap<>();
        for (Video video : videoList) {
            ObjectId vid = video.getId();
            Integer commentCount = this.videoApi.queryCommentCount(vid.toString());
            Long likeCount = this.videoApi.queryLikeCount(vid.toString());
            likeCountMap.put(vid,likeCount);
            commentCountMap.put(vid,commentCount);
        }

        List<VideoVo> videoVoList = videoList.stream()
                .map(video -> {
                    // VideoVo videoVo = BeanUtil.toBeanIgnoreError(userInfoMap.get(video.getUserId()), VideoVo.class);
                    VideoVo videoVo = BeanUtil.toBeanIgnoreError(video, VideoVo.class);
                    videoVo.setId(Convert.toInt(video.getId()));
                    videoVo.setNickname(userInfoMap.get(video.getUserId()).getNickName());
                    videoVo.setCreateDate(Convert.toLong(video.getCreated()));
//                    videoVo.setCreateDate(10000);
                    videoVo.setReportCount(RandomUtil.randomInt(5,100));
                    videoVo.setLikeCount(Convert.toInt(likeCountMap.get(video.getId())));
                    videoVo.setForwardingCount(RandomUtil.randomInt(5,39));
                    videoVo.setCommentCount(Convert.toInt(commentCountMap.get(video.getId())));
                    return videoVo;
                }).collect(Collectors.toList());

        pageResult.setItems(videoVoList);

        return pageResult;
    }

    /**
     * 登陆记录
     *
     * @param page
     * @param pageSize
     * @param logTime
     * @param descending
     * @param uid
     * @return
     */
    public Object queryLoginHistoryPage(Integer page, Integer pageSize, String logTime, String descending, Long uid) {


        //  TODO userId 登陆一次,定义一个count ++
        //TODO  将count存到redis中,实时更新,需要是查找即可
        return "loginHistory";
    }
}